package com.uplooking.filter;

import java.io.IOException;
import java.security.Security;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.uplooking.constant.TokenConstants;
import com.uplooking.pojo.UserVO;
import com.uplooking.service.impl.UserServiceImpl;
import com.uplooking.util.TokenUtils;

@Component
public class TokenFilter extends OncePerRequestFilter {

	@Autowired
	private UserServiceImpl userService;
	
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		//获取Cookie中token信息
		if(request.getCookies()!=null) {
			for(Cookie cookie:request.getCookies()) {
				if(TokenConstants.TokenKey.equals(cookie.getName())) {
					String token = cookie.getValue();
					String username = TokenUtils.getAudience(token);
					UserVO userVO = (UserVO) userService.loadUserByUsername(username);
					if(userVO!=null) {
						//判断
						TokenUtils.checkToken(token, userVO.getPassword());
						//单点登录 写入当前状态
						UsernamePasswordAuthenticationToken authentication = 
								new UsernamePasswordAuthenticationToken(userVO, null, userVO.getAuthorities());
						
						SecurityContextHolder.getContext().setAuthentication(authentication);
					}
				}
			}
		}

		//放行
		filterChain.doFilter(request, response);

	}

}
